package com.pyk.interceptors;


import com.pyk.utils.JwtUtil;
import com.pyk.utils.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 这个类的具体功能就是登录验证的拦截器  具体的实现方法
 */
@Component //这个类会生成bean 并插入IOC容器
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,  HttpServletResponse response,  Object handler) throws Exception {
        //令牌验证
        String token= request.getHeader("Authorization");
        //验证token
        try{
            Map<String,Object> claims = JwtUtil.parseToken(token);//调用工具
            ThreadLocalUtil.set(claims);
            return true;//放行
        }
        catch (Exception e) {
            //响应码为401
            response.setStatus(401);
            return false;//不放行
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空本地线程ThreadLocal的数据
        ThreadLocalUtil.remove();
    }
}
